package com.cxx.autoconfigure.web;

import com.cxx.autoconfigure.config.CustomProperties;
import com.cxx.autoconfigure.util.WebUtils;
import com.cxx.framework.web.ErrorResponse;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Import;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;


/**
 * 请求和响应体拦截器
 * RequestBodyAdvice, ResponseBodyAdvice主要发生在Controller执行前后：
 * 1. preHandle()：请求处理前
 * 2. beforeBodyRead：请求体反序列化前
 * 3. @RequestBody：Controller方法参数绑定
 * 4. Controller：请求处理
 * 5. beforeBodyWrite()：响应体序列化之前
 * 6. postHandle()：请求处理后
 * 7. 视图渲染
 * 8. afterCompletion()：请求结束
 */
@ControllerAdvice
@Import({CustomProperties.class})
public class AuditBodyAdvice implements RequestBodyAdvice, ResponseBodyAdvice<Object> {
    @Resource
    private CustomProperties customProperties;

    private final ObjectMapper objectMapper = new ObjectMapper();


    private static final Logger logger = LoggerFactory.getLogger(AuditBodyAdvice.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 判断是否为需要审计的包
        String auditPackages = customProperties.getBasePackage();
        return WebUtils.checkIsAuditPackages(methodParameter.getDeclaringClass().getPackage(), auditPackages)
                && AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        return inputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 入参结束
        try {
            String jsonBody = objectMapper.writeValueAsString(body);
            logger.info("<AuditRequest> {}", jsonBody);
        } catch (JsonProcessingException e) {
            logger.info("<AuditResponse> {}", body);
        }
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return body;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 判断是否为需要审计的包
        String auditPackages = customProperties.getBasePackage();
        return WebUtils.checkIsAuditPackages(returnType.getDeclaringClass().getPackage(), auditPackages)
                && AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 出参结束
        if (body != null && !(body instanceof ErrorResponse)) {
            try {
                String jsonBody = objectMapper.writeValueAsString(body);
                logger.info("<AuditResponse> {}", jsonBody);
            } catch (JsonProcessingException e) {
                logger.info("<AuditResponse> {}", body);
            }
        }
        return body;
    }

}
